#include "registredialog.h"
#include "ui_registredialog.h"
#include <QFile>
#include <QDir>
#include <QRegExp>
#include <QImage>
#include <QBuffer>
RegistreDialog::RegistreDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegistreDialog)
{
    ui->setupUi(this);
    this->setFixedSize(this->size());
    network_manager = new QNetworkAccessManager();
    connect(network_manager, SIGNAL(finished(QNetworkReply*)), SLOT(OnFinished(QNetworkReply*)));
    CurrentState=GET_PARAMETRS_LIST;
    GetParametrsList=QUrl("http://www.google.com/recaptcha/api/challenge?k=6LdLPMASAAAAAIjSZLuC5Pg04-lOB-nHVmCXbyNP");
    CaptchaUrl=QUrl("http://www.google.com/recaptcha/api/image?c=");
    CurrentCaptchaUrl=QUrl("");
    RegisterUrl=QUrl("http://shotscreens.appspot.com/account/register/");

    RegInfo.UserName.clear();
    RegInfo.UserPassword.clear();
    RegInfo.CaptchaText.clear();
    ui->lineEdit->setFocus();
    ui->lineEdit->setText("");
    ui->lineEdit_2->setText("");
    ui->lineEdit_3->setText("");
    ui->lineEdit_4->setText("");
}

RegistreDialog::~RegistreDialog()
{
    delete ui;
}

void RegistreDialog::on_pushButton_clicked()
{
    this->close();
}
void RegistreDialog::ConstructGetChallengeQuery()
{
    ui->lineEdit->setFocus();
    CurrentState = GET_PARAMETRS_LIST;
    req=QNetworkRequest(GetParametrsList);
    request.clear();
    network_manager->get(req);
}

void RegistreDialog::ConstructGetCaptchaQuery()
{
    CurrentState = GET_IMAGE;
    CurrentCaptchaUrl=QUrl(CaptchaUrl.toString() + RegInfo.challenge);
    request.clear();
    data.clear();
    req=QNetworkRequest(CurrentCaptchaUrl);
    network_manager->get(req);
}

void RegistreDialog::OnFinished(QNetworkReply *reply)
{
        int total_bytes=reply->bytesAvailable();
        Q_UNUSED(total_bytes);
        data=reply->readAll();

        QString read_buffer(data);


        QFile picture_file;
        QDir dir;

        QBuffer buffer;

        int pos=0;
        if(reply->error())
        {
            QString msgString;
            msgString.append("Network error: ");
            msgString.append(reply->errorString());
            MessageBox.critical(this,QString(""),msgString,QMessageBox::Ok,QMessageBox::NoButton);
            return;
        }

        switch(CurrentState)
        {
            case GET_PARAMETRS_LIST:
                pos=read_buffer.indexOf("challenge : '") + QString("challenge : '").length();
                read_buffer=read_buffer.mid(pos);
                pos=read_buffer.indexOf("'");
                RegInfo.challenge=read_buffer.mid(0,pos);
                ConstructGetCaptchaQuery();
                break;
        case GET_IMAGE:
                image=QImage::fromData(data);
                buffer.open(QIODevice::ReadWrite);
                buffer.write(data);
                ui->label_5->setPixmap(QPixmap::fromImage(image));
                buffer.close();
                break;
        case SEND_POST_QUERY:
                read_buffer=reply->header(QNetworkRequest::LocationHeader).toString();
                if(read_buffer.length()<2)
                {
                    MessageBox.critical(this,QString(""),QString("Registration error!"),QMessageBox::Ok,QMessageBox::NoButton);
                    ui->lineEdit->setText("");
                    ui->lineEdit_2->setText("");
                    ui->lineEdit_3->setText("");
                    ui->lineEdit_4->setText("");
                    ui->lineEdit->setEnabled(true);
                    ui->lineEdit_2->setEnabled(true);
                    ui->lineEdit_3->setEnabled(true);
                    ui->lineEdit_4->setEnabled(true);

                    ui->pushButton_3->setEnabled(true);
                    ui->pushButton_2->setEnabled(true);
                    ConstructGetChallengeQuery();
                    return;
                }
                if(read_buffer.compare(QString("http://shotscreens.appspot.com/account/register/complete/")))
                {
                    MessageBox.information(this,QString(""),QString("Registration complete!\nPlease check your e - mail address and activate your account now."),QMessageBox::Ok,QMessageBox::NoButton);
                    this->hide();

                }
                else
                {
                    MessageBox.critical(this,QString(""),QString("Registration error!"),QMessageBox::Ok,QMessageBox::NoButton);
                    ui->lineEdit->setText("");
                    ui->lineEdit_2->setText("");
                    ui->lineEdit_3->setText("");
                    ui->lineEdit_4->setText("");
                    ConstructGetChallengeQuery();
                }
                ui->lineEdit->setEnabled(true);
                ui->lineEdit_2->setEnabled(true);
                ui->lineEdit_3->setEnabled(true);
                ui->lineEdit_4->setEnabled(true);

                ui->pushButton_3->setEnabled(true);
                ui->pushButton_2->setEnabled(true);

                break;
        default:
                break;

        }

}

void RegistreDialog::on_pushButton_2_clicked()
{
    QRegExp checker;
    checker.setPattern("^[-a-z0-9!#$%&'*+/=?^_`{|}~]+(?:\\.[-a-z0-9!#$%&'*+/=?^_`{|}~]+)*@(?:[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\\.)*(?:aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ru|[a-z][a-z])$");
    if(!checker.exactMatch(ui->lineEdit->text()))
    {
        MessageBox.setModal(true);
        MessageBox.critical(this,QString(""),QString("Your email is not valid!"),QMessageBox::Ok,QMessageBox::NoButton);
        return;
    }

    if(ui->lineEdit->text().length() == 0 || ui->lineEdit_2->text().length() == 0 || ui->lineEdit_3->text().length() == 0 || ui->lineEdit_4->text().length() == 0)
    {
        MessageBox.setModal(true);
        MessageBox.critical(this,QString(""),QString("Not all fields are filled"),QMessageBox::Ok,QMessageBox::NoButton);
        return;
    }

    if(ui->lineEdit_2->text()!=ui->lineEdit_3->text())
    {
        MessageBox.setModal(true);
        MessageBox.critical(this,QString(""),QString("Your passwords are different!"),QMessageBox::Ok,QMessageBox::NoButton);
        return;
    }

    req=QNetworkRequest(RegisterUrl);
    data.clear();
    request.clear();
    CurrentState = SEND_POST_QUERY;
    request=request.append("username=");
    request=request.append(ui->lineEdit->text().toAscii().data());
    request=request.append("&email=");
    request=request.append(ui->lineEdit->text().toAscii().data());

    request=request.append("&password1=");
    request=request.append(ui->lineEdit_2->text().toAscii().data());
    request=request.append("&password2=");
    request=request.append(ui->lineEdit_2->text().toAscii().data());
    request=request.append("&recaptcha_challenge_field=");
    request=request.append(RegInfo.challenge.toAscii().data());
    request=request.append("&recaptcha_response_field=");
    request=request.append(ui->lineEdit_4->text().toAscii().data());

    ui->lineEdit->setEnabled(false);
    ui->lineEdit_2->setEnabled(false);
    ui->lineEdit_3->setEnabled(false);
    ui->lineEdit_4->setEnabled(false);

    ui->pushButton_3->setEnabled(false);
    ui->pushButton_2->setEnabled(false);

    network_manager->post(req,request);

}

void RegistreDialog::on_pushButton_3_clicked()
{
    ConstructGetChallengeQuery();
}

void RegistreDialog::OnLoad()
{
    ui->lineEdit->setText("");
    ui->lineEdit_2->setText("");
    ui->lineEdit_3->setText("");
    ui->lineEdit_4->setText("");
}
